//该文件专门用于创建整个应用的路由器
import VueRouter from "vue-router"
//引入组件
import About from "../pages/About"
import Home from "../pages/Home"
import Message from "../pages/Message"
import News from "../pages/News"
import Detail from "../pages/Detail"

//创建并暴露一个路由器
const router = new VueRouter({
    routes: [
        {
            name: "guangyu",
            path: "/about",
            component: About,
            meta: { title: "关于" },
        },
        {
            name: "zhuye",
            path: "/home",
            component: Home,
            meta: { title: "主页" },
            children: [
                {
                    // 不要再加/
                    name: "xiaoxi",
                    path: "message",
                    meta: { isAuth: true, title: "消息" },
                    component: Message,
                    children: [
                        {
                            name: "xiangqing",
                            //使用占位符告诉浏览器，我的id和title在哪里
                            path: "detail",
                            component: Detail,
                            meta: { isAuth: true, title: "详情" },
                            //props的第三种写法，值为函数，
                            props($route) {
                                return {
                                    id: $route.query.id,
                                    title: $route.query.title,
                                }
                            }
                        }
                    ]
                },
                {
                    name: "xinwen",
                    path: "news",
                    component: News,
                    meta: { isAuth: true, title: "新闻" },
                    //独享路由守卫
                    beforeEnter(to, from, next) {
                        //判断是否需要鉴权
                        if (to.meta.isAuth) {
                            if (localStorage.getItem("school") === "atguigu2") {
                                next();
                            }
                            else {
                                alert("学校名不对，无权限查看");
                            }
                        } else {
                            next();
                        }
                    }
                }
            ]
        }
    ]
})

//全局前置路由守卫，beforeEach每一次路由切换之前被调用（初始化也被调用一次）
/* router.beforeEach((to, from, next) => {
    //判断是否需要鉴权
    if (to.meta.isAuth) {
        if (localStorage.getItem("school") === "atguigu") {
            next();
        }
        else {
            alert("学校名不对，无权限查看");
        }
    } else {
        next();
    }
}); */

//全局后置路由守卫，beforeEach每一次路由切换之后被调用（初始化也被调用一次）
router.afterEach((to, from) => {
    document.title = to.meta.title || "硅谷系统";
});

export default router;

